package music

import (
	"bytes"
	"context"
	"crypto/md5"
	"fmt"
	"io"
	"mime/multipart"
	"time"

	"github.com/zeromicro/x/errors"

	"go-weixin/app/music/musicapi/internal/svc"
	"go-weixin/app/music/musicapi/internal/types"
	"go-weixin/app/music/musicrpc/pb/proto/music"

	"github.com/zeromicro/go-zero/core/logx"
)

type MusicStreamDataLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMusicStreamDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MusicStreamDataLogic {
	return &MusicStreamDataLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MusicStreamDataLogic) MusicStreamData(req *types.MusicStreamDataReq, file multipart.File, fileHeader *multipart.FileHeader) (resp *types.MusicStreamDateResp, err error) {
	ctx, canelFunc := context.WithTimeout(context.Background(), 25*time.Second)
	defer canelFunc()
	byteData := make([]byte, fileHeader.Size)
	file.Read(byteData)
	fileHash := fmt.Sprintf("%x", md5.Sum(byteData))
	defer file.Close()
	m, err := l.svcCtx.MusicRpc.MusicMd5Exist(ctx, &music.MusicMd5ExeistReq{Md5: fileHash})
	if err != nil {
		return nil, err
	}

	resp = new(types.MusicStreamDateResp)
	if m.Domain != "" {
		resp.Domain = m.Domain
		resp.Md5 = m.Md5
		resp.Path = m.Path
		resp.Size = m.Size
		return
	}

	stream, err := l.svcCtx.MusicRpc.MusicStreamData(ctx)
	reader := bytes.NewReader(byteData)
	buf := make([]byte, 5120)
	for {
		num, err := reader.Read(buf)
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, errors.New(7000, "读取文件异常: "+err.Error())
		}
		err = stream.Send(&music.MusicStreamDataReq{
			Filename: fileHeader.Filename,
			Size:     fileHeader.Size,
			FileByte: buf[:num],
		})
		if err != nil {
			return nil, errors.New(7000, "文件rpc流传输异常"+err.Error())
		}
	}
	res, err := stream.CloseAndRecv()
	if err != nil {
		return nil, errors.New(7000, "rpc返回异常"+err.Error())
	}
	resp.Domain = res.Domain
	resp.Md5 = res.Md5
	resp.Path = res.Path
	resp.Size = res.Size
	return resp, nil
}
